import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/custom_text_field.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/round_checkbox.dart';
import 'package:qunaimedical/im/im_utils.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/register.dart';
import 'package:qunaimedical/pages/reset_password.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/log_util.dart';
import 'package:qunaimedical/utils/navigator_util.dart';
import 'package:qunaimedical/utils/sp_util.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/navigation.dart';
import 'package:qunaimedical/values/urls.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final String _tag = '_LoginPageState';

  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  bool _showPwd = false;
  bool _checkboxSelected = false;

  @override
  void initState() {
    super.initState();
    if (kDebugMode) {
      _accountController.text = "18710711835";
      _pwdController.text = "000000";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("登录/注册")),
      body: CommonUtil.generateWidgetOfWideScreen(_buildBody()),
    );
  }

  Widget _buildBody() {
    return ListView(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
      children: [
        Container(
          padding: const EdgeInsets.only(left: 20, right: 20, bottom: 16),
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            children: [
              CustomTextField(
                label: "手机号",
                controller: _accountController,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(11),
                ],
                textInputAction: TextInputAction.next,
                hintText: "请输入手机号",
                onChanged: (value) {
                  setState(() {});
                },
                suffixIcon: _accountController.text.isNotEmpty
                    ? IconButton(
                        icon: const Icon(
                          CupertinoIcons.xmark_circle,
                          color: Colors.grey,
                        ),
                        onPressed: () {
                          setState(() {
                            _accountController.clear();
                          });
                        })
                    : null,
              ),
              CustomTextField(
                label: "密码",
                controller: _pwdController,
                hintText: "请输入密码",
                obscureText: !_showPwd,
                suffixIcon: IconButton(
                    icon: _showPwd
                        ? const Icon(CupertinoIcons.eye, color: Colors.grey)
                        : Image.asset(
                            'assets/images/ic_eye_close.png',
                            width: 20,
                            height: 20,
                            color: Colors.grey,
                          ),
                    onPressed: () {
                      setState(() {
                        _showPwd = !_showPwd;
                      });
                    }),
              ),
            ],
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            TextButton(
                onPressed: () {
                  if (_checkboxSelected) {
                    navigateTo(context, ResetPasswordPage());
                  } else {
                    _showAgreeToast();
                  }
                },
                child: Text(
                  "忘记密码",
                  style: TextStyle(color: Theme.of(context).primaryColor),
                )),
            TextButton(
                onPressed: () {
                  if (_checkboxSelected) {
                    navigateTo(context, RegisterPage());
                  } else {
                    _showAgreeToast();
                  }
                },
                child: Text(
                  "注册账号",
                  style: TextStyle(color: Theme.of(context).primaryColor),
                )),
          ],
        ),
        _buildAgreement(),
        PrimaryButton(
          "登录",
          margin: const EdgeInsets.symmetric(vertical: 16),
          onPressed: _login,
        ),
      ],
    );
  }

  Widget _buildAgreement() {
    return Container(
      alignment: Alignment.bottomCenter,
      margin: const EdgeInsets.only(top: 30),
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.only(right: 6, left: 10),
            child: RoundCheckBox(
              status: _checkboxSelected,
              onTap: _handleRoundCheckBoxClicked,
            ),
          ),
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              children: [
                TextSpan(
                  text: "阅读并同意",
                  style: Theme.of(context).textTheme.bodyMedium,
                  recognizer: TapGestureRecognizer()
                    ..onTap = _handleRoundCheckBoxClicked,
                ),
                TextSpan(
                  text: '「服务条款」',
                  style: TextStyle(
                    fontSize: 14.0,
                    decoration: TextDecoration.underline,
                    color: Theme.of(context).primaryColor,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap =
                        () => navigateTo(context, WebPage(url: Urls.TERMS)),
                ),
                TextSpan(
                  text: "和",
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
                TextSpan(
                  text: '「隐私政策」',
                  style: TextStyle(
                    fontSize: 14.0,
                    decoration: TextDecoration.underline,
                    color: Theme.of(context).primaryColor,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap =
                        () => navigateTo(context, WebPage(url: Urls.PRIVACY)),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _showAgreeToast() {
    ToastUtil.show("请先阅读并同意服务条款");
  }

  void _handleRoundCheckBoxClicked() {
    setState(() {
      _checkboxSelected = !_checkboxSelected;
    });
  }

  void _login() async {
    if (!_checkboxSelected) {
      _showAgreeToast();
      return;
    }
    try {
      String userName = _accountController.text.trim();
      String password = _pwdController.text.trim();
      DialogUtil.showWaitDialog(context);
      Response response =
          await XHttp.instance.get(Urls.LOGIN, queryParameters: {
        "userName": userName,
        "password": password,
      });
      if (mounted) {
        Navigator.pop(context);
        if (response.statusCode == 200 && response.data != null) {
          var result = json.decode(response.data);
          if (result["result"] == "login_fail") {
            ToastUtil.show("账号或密码错误，请重试。");
          } else {
            // 登录成功
            var qaUser = QAUser.fromJson(result["data"]);
            context.read<StoreInfo>().updateQAUser(qaUser);
            // 保存登录信息到本地。
            SPUtil.setUserName(userName);
            SPUtil.setPassword(password);
            // 发送登录成功通知
            eventBus.fire(EventBusMessage.loginSuccess);
            // 登录IM账号，没有的话直接注册。
            await IMUtils.signIn(qaUser.id);
            Navigator.popUntil(
                context, ModalRoute.withName(Navigation.home.name));
          }
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        Navigator.pop(context);
        CommonUtil.catchDioError(e);
      }
    } on EMError catch (e) {
      if (mounted) {
        if (e.code == 204) {
          // 204 , User dosn't exist
          QAUser? user = context.read<StoreInfo>().qaUser;
          if (user != null) {
            bool status = await IMUtils.signUp(user.id);
            Log.d(_tag, "IM注册结果：$status");
            if (status) {
              await IMUtils.signIn(user.id);
              Navigator.popUntil(
                  context, ModalRoute.withName(Navigation.home.name));
            } else {
              ToastUtil.show("IM账号注册失败！");
            }
          }
        }
      }
    }
  }
}
